import React, { Component } from 'react';

import './index.less';

import {
    base,
    toast
} from 'nc-lightapp-front';

import UserGroupRefer from '../../../../public/components/UserGroupRefer';

import getCreateUserData from './request/getCreateUserData';
import createUserPost from './request/createUserPost';

import language from '../../language';

const {
    NCModal,
    NCButton,
    NCSelect
} = base;
const { NCOption } = NCSelect;
const {
    Body: NCModalBody,
    Header: NCModalHeader,
    Footer: NCModalFooter
} = NCModal;

const createUser = 'createuser';

class CreateUserModal extends Component {
    constructor(props) {
        super(props);

        this.state = {
            userGroup: [],
            userCodeType: [],
            codeType: {
                // label: '人员编码',
                // key: 'psncode'
            }, // 选的编码形式
            flag: true
        };

        this.closeModal = this.closeModal.bind(this);
        this.initModal = this.initModal.bind(this);
        this.changeRefer = this.changeRefer.bind(this);
        this.createUserPost = this.createUserPost.bind(this);
        this.userCodeChange = this.userCodeChange.bind(this);
        this.getUserData = this.getUserData.bind(this);
        this.checkIsHaveUserCode = this.checkIsHaveUserCode.bind(this);
    }

    createUserPost() {

        const {
            editTable: {
                getCheckedRows,
                getAllData
            },
            humanResourceOrganizationValue: {
                refpk
            }
        } = this.props;

        let {
            userGroup
        } = this.state;

        userGroup = Array.isArray(userGroup) ? userGroup : [userGroup];

        let userGroupPk = userGroup.map((item) => {
            return item.refpk
        });

        let rows = [];

        getCheckedRows(createUser).map((item) => {
            rows.push(item.data);
        });

        let userCode = this.checkIsHaveUserCode(rows);
        if (!userCode) {
            return false
        }
        // let allUserCreated = rows.every((item) => {
        //     return item.values.isRelated.value == true
        // })
        // if (allUserCreated) {
        //     toast({
        //         color: 'warning',
        //         content: language['hi6007-000308'] || '所选数据已生成用户，请重新选择'// 所选数据已生成用户，请重新选择
        //     });
        //     return false
        // }
        let postData = {
            model: {
                areaType: 'table',
                areacode: null,
                rows: rows
            },
            pk_org: refpk,
            pk_userGroup: userGroupPk.join(',')
        };
        createUserPost(postData)
            .then((res) => {
                if (res.success) {
                    toast({
                        color: 'success',
                        content: language['hi6007-000184'] // 生成用户成功
                    });
                    this.closeModal();
                }
            });
    }
    // 当邮箱前缀等没有数据时进行校验，让用户自己填写
    checkIsHaveUserCode(rows) {
        if (rows.length === 0) {
            toast({
                color: 'warning',
                content: language['hi6007-000309'] || '请选择你要操作的数据'// 请选择你要操作的数据
            });
            return false
        }
        let len = rows.length;
        for (let index = 0; index < len; index++) {
            const element = rows[index].values.code.value;
            if (!element) {
                toast({
                    color: 'warning',
                    content: language['hi6007-000310'] || '用户编码不能为空'// 用户编码不能为空
                });
                return false
            }
        }

        return true
    }

    changeRefer(value) {
        this.setState({
            userGroup: value
        });
    }

    initModal() {
        if (this.state.flag) {
            let userCodeType = [
                {
                    label: language['hi6007-000315'] || '人员编码',
                    key: 'psncode'
                }, {
                    label: language['hi6007-000316'] || '姓名简拼',
                    key: 'shortname'
                }, {
                    label: language['hi6007-000317'] || '手机号',
                    key: 'phone'
                }, {
                    label: language['hi6007-000302'] || '电子邮件前缀',
                    key: 'email'
                }
            ]
            this.setState({
                userCodeType: userCodeType,
                codeType: {
                    label: language['hi6007-000315'] || '人员编码',
                    key: 'psncode'
                }
            }, () => {
                this.getUserData()
            })
        } else {
            this.getUserData()
        }
    }
    getUserData() {
        const {
            humanResourceOrganizationValue: {
                refpk
            },
            selectedRows,
            editTable: {
                setTableData,
                setStatus
            }
        } = this.props;
        let pkPsnJob = [];

        selectedRows.map((item) => {
            pkPsnJob.push(item.data.values.pk_psnjob.value);
        });

        let postData = {
            param_str: pkPsnJob.join(','),
            pk_org: refpk,
            codetype: this.state.codeType.key
        };

        setStatus(createUser, 'edit');
        getCreateUserData(postData)
            .then((res) => {
                if (res.success) {
                    let data = res.data.createuser;

                    data.rows.forEach((item) => {
                        if (item.values['isRelated'].value) {
                            item.values['code']['disabled'] = true;
                        }
                        // 已经生成用户的数据的checkout设为disabled
                        item['disabled'] = item.values['isRelated'].value;
                    });
                    setTableData(createUser, data);
                }
            });
    }
    userCodeChange(val) {
        let list = this.state.userCodeType;
        let selectedObj = list.filter(item => { return item.key === val })[0] || {};
        this.setState({
            flag: false,
            codeType: selectedObj
        }, () => {
            this.initModal()
        })
    }
    closeModal() {
        this.setState({ flag: true })
        this.props.onClose();
        this.setState({
            userGroup: []
        })
    }

    render() {
        const {
            visible,
            editTable: {
                createEditTable
            },
            meta
        } = this.props;

        const {
            userGroup,
            userCodeType,
            codeType
        } = this.state

        const template = meta.getMeta();

        if (template['createuser'] && template['createuser'].items) {
            template['createuser'].items.map((item) => {
                item.width = '120px';
            });
        }

        return (
            <NCModal
                show={visible}
                onHide={this.closeModal}
                className="info-maintenance-create-user-modal"
                onEntered={this.initModal}
            >
                <NCModalHeader
                    closeButton={true}
                >
                    {language['hi6007-000042']}{/* 国际化处理： 生成用户*/}
                </NCModalHeader>
                <NCModalBody>
                    <div className="create-user-modal-content">
                        <div className="create-user-modal-content-head">
                            <div className="create-user-modal-refer">
                                <span className="user-group-refer-label">
                                    {language['hi6007-000043']}{/* 国际化处理： 用户所属的用户组*/}
                                </span>
                                <span className="user-group-refer">
                                    <UserGroupRefer
                                        {...this.props}
                                        onChange={this.changeRefer}
                                        value={userGroup}
                                        setState={this.setState.bind(this)}
                                    />
                                </span>
                            </div>
                            <div className="create-user-modal-select">
                                <span className="user-group-select-label">{language['hi6007-000303'] || '用户编码引用'}</span>
                                <NCSelect
                                    showClear={false}
                                    value={codeType.label}
                                    style={{ width: 200, marginRight: 6, display: 'inline-block' }}
                                    onChange={this.userCodeChange}
                                >
                                    {userCodeType.map((item) => {
                                        return (
                                            <NCOption key={item.key}>{item.label}</NCOption>
                                        )
                                    })}

                                </NCSelect>
                            </div>
                        </div>
                        <div className="create-user-modal-table">
                            {createEditTable(createUser, {
                                showCheck: true,
                                onSelected: this.selectRowHandle
                            })}
                        </div>
                    </div>
                </NCModalBody>
                <NCModalFooter>
                    <div className="create-user-button-wrapper">
                        <NCButton
                            colors="primary"
                            onClick={this.createUserPost}
                        >
                            {language['hi6007-000004']}{/* 国际化处理： 确定*/}
                        </NCButton>
                        <NCButton
                            onClick={this.closeModal}
                            colors="secondary"
                        >
                            {language['hi6007-000005']}{/* 国际化处理： 取消*/}
                        </NCButton>
                    </div>
                </NCModalFooter>
            </NCModal>
        );
    }
}

export default CreateUserModal;
